package GoodsService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/request/GoodsReq"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/service-member/CartService"
	"github.com/gogf/gf/frame/g"
	"time"
)

func Collection(ctx context.Context, parames *GoodsReq.Collection) *response.JsonResponse {
	goodsModel := GetGoodsModelRaw(ctx, parames.Id)
	if goodsModel == nil {
		return response.FailByRequestMessage(nil, "找不到商品")
	}

	count, err := toolsDb.GetUnSafaTableAddDeleteWhere(
		ctx,
		"member_collection").Where(g.Map{
		"member_id": parames.MemberId,
		"goods_id":  parames.Id,
	}).Fields("1").Count()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	if count < 1 {
		// 不存在
		_, err := toolsDb.GetUnSafaTableAddDeleteWhere(
			ctx,
			"member_collection").Insert(g.Map{
			"member_id": parames.MemberId,
			"goods_id":  parames.Id,
			"create_at": time.Now().Unix(),
		})
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}

		doDelCart(ctx, parames.CartId, parames.MemberId)

		return response.SuccessByRequestMessage(nil, "收藏成功")
	} else {
		// 存在
		_, errUpdate := toolsDb.GetUnSafaTableAddDeleteWhere(
			ctx,
			"member_collection").Where(g.Map{
			"member_id": parames.MemberId,
			"goods_id":  parames.Id,
		}).Delete()
		if errUpdate != nil {
			return response.FailByRequestMessage(nil, errUpdate.Error())
		}

		doDelCart(ctx, parames.CartId, parames.MemberId)

		return response.SuccessByRequestMessage(nil, "取消收藏成功")
	}
}

func doDelCart(ctx context.Context, cartId int, memberId int) {
	if cartId < 1 {
		return
	}

	_, err := CartService.BaseDel(ctx, cartId, memberId)
	if err != nil {
		return
	}
}
